#include <QtCore>
#include "volume.hpp"
#include "thinning.h"
#include "stopwatch.hpp"
#include "logger.hpp"

int main(int argc,char *argv[]) {
  int error;
  if (argc!=3) {
    printf("Usage: skeletonise in_file out_file.[z]rawx\n   or: skeletonise input_folder output_folder\n");
    exit(1);
  }
  Skeletoniser skel;
  Stopwatch sw;
  Logger logger;
  QString input(argv[1]);
  QString output(argv[2]);
  QFileInfo inputFileInfo(input);
  QFileInfo outputFileInfo(output);
  if (inputFileInfo.isFile() && (outputFileInfo.suffix()==QString("rawx") || outputFileInfo.suffix()==QString("zrawx"))) {
    QString fileName=inputFileInfo.absoluteFilePath();
    Volume vol(fileName,false,false);
    dim3 dim;
    dim.x=vol.size().x();
    dim.y=vol.size().y();
    dim.z=vol.size().z();
    error=setupSkeletoniser(&skel,dim,vol.numVoxels());
    sw.start();
    error=skeletonise(&skel,vol.data());
    sw.stop();
    sw.print("Skeletonised");
    logger << sw.toString("Skeletonised") << endl;
    QString outFileName=outputFileInfo.absoluteFilePath();
    vol.setSkeleton(true);
    vol.setFileName(outFileName);
    vol.writeVolumeFile();
    cleanUp(&skel);
  } else if (inputFileInfo.isDir() && outputFileInfo.isDir()) {
    QDir inputDir(input);
    QDir outputDir(output);
    inputDir.setFilter(QDir::Files);
    QStringList nameFilters;
    nameFilters << "*.rawx" << "*.zrawx";
    inputDir.setNameFilters(nameFilters);
    inputDir.setSorting(QDir::Name);
    QStringList files=inputDir.entryList();
    if (files.size()>0) {
      QString fileName=inputDir.absoluteFilePath(files.takeFirst());
      qDebug() << fileName;
      Volume *vol=new Volume(fileName,false,false);
      dim3 dim;
      dim.x=vol->size().x();
      dim.y=vol->size().y();
      dim.z=vol->size().z();
      error=setupSkeletoniser(&skel,dim,vol->numVoxels());
      sw.start();
      error=skeletonise(&skel,vol->data());
      sw.stop();
      sw.print("Skeletonised");
      logger << sw.toString("Skeletonised") << endl;
      QString outFileName=outputDir.absoluteFilePath(QFileInfo(fileName).fileName());
      vol->setSkeleton(true);
      vol->setFileName(outFileName);
      vol->writeVolumeFile();
      delete vol;
      QStringListIterator i(files);
      while (i.hasNext()) {
        fileName=inputDir.absoluteFilePath(i.next());
        qDebug() << fileName;
        vol=new Volume(fileName,false,false);
        sw.start();
        error=skeletonise(&skel,vol->data());
        sw.stop();
        sw.print("Skeletonised");
        logger << sw.toString("Skeletonised") << endl;
        outFileName=outputDir.absoluteFilePath(QFileInfo(fileName).fileName());
        vol->setSkeleton(true);
        vol->setFileName(outFileName);
        vol->writeVolumeFile();
        delete vol;
      }
      cleanUp(&skel);
    }   
  } else {
    printf("Not valid input.\n");
    exit(1);
  }
  logger.save(QString("%1.log").arg(outputFileInfo.baseName()));
}
